package cn.alex.sso.project.service.impl;

import cn.alex.sso.framework.global.ServiceException;
import cn.alex.sso.framework.util.TreeBuilder;
import cn.alex.sso.project.entity.SysDept;
import cn.alex.sso.project.mapper.SysDeptMapper;
import cn.alex.sso.project.mapper.SysUserDeptMapper;
import cn.alex.sso.project.service.SysDeptService;
import cn.alex.sso.project.sync.event.DeptAbstractDataSyncEvent;
import cn.alex.sso.project.sync.module.DeptDataSyncModule;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author Alex
 * @description 针对表【sys_dept(部门表)】的数据库操作Service实现
 * @createDate 2024-09-24 17:05:38
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    private final SysUserDeptMapper userDeptMapper;

    @Override
    public List<SysDept> getList(SysDept entity) {
        return baseMapper.selectList(baseMapper.getQueryWrapper(entity));
    }

    @Override
    public List<SysDept> getTree(SysDept entity) {
        List<SysDept> list = getList(entity);
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }

        return TreeBuilder.build(list, "id", "parentId", "children");
    }

    @Override
    public void add(SysDept entity) {
        entity.setCreatedTime(new Date());
        entity.setUpdatedTime(new Date());
        baseMapper.insert(entity);

        SpringUtil.getApplicationContext().publishEvent(new DeptAbstractDataSyncEvent(this, entity, DeptDataSyncModule.Trigger.ADD));
    }

    @Override
    public void edit(SysDept entity) {
        entity.setUpdatedTime(new Date());
        baseMapper.updateById(entity);

        SpringUtil.getApplicationContext().publishEvent(new DeptAbstractDataSyncEvent(this, entity, DeptDataSyncModule.Trigger.EDIT));
    }

    @Override
    public void del(List<Long> ids) {
        boolean childExist = baseMapper.exists(new LambdaQueryWrapper<SysDept>().in(SysDept::getParentId, ids));
        if (childExist) {
            throw new ServiceException("该部门下存在子部门，无法删除");
        }

        List<Long> userIdList = userDeptMapper.getUserIdListByDeptId(ids);
        if (CollUtil.isNotEmpty(userIdList)) {
            throw new ServiceException("该部门下存在用户，无法删除");
        }
        baseMapper.deleteByIds(ids);

        SpringUtil.getApplicationContext().publishEvent(new DeptAbstractDataSyncEvent(this, ids, DeptDataSyncModule.Trigger.DELETE));
    }
}




